package com.kehutong.contact.service.impl;

import com.kehutong.common.util.Token;
import com.kehutong.contact.entity.Contact;
import com.kehutong.contact.entity.ContactDynamics;
import com.kehutong.contact.entity.Customer;
import com.kehutong.contact.service.CustomerRecordService;
import com.kehutong.contact.service.CustomerService;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author liujinwang
 * description:
 */
@WebService("/crm/customer/service")
public class CustomerServiceImpl implements CustomerService {
    private static final Logger logger = LoggerFactory.getLogger(CustomerServiceImpl.class);

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private CustomerRecordService customerRecordService;

    /**
     * 根据条件获取客户列表
     * @param jsonObject 查询对象
     * @return 客户列表
     */
    @ReqMapping("/page")
    @Override
    public Page<Customer> page(JSONObject jsonObject) {
        FindPage<Customer> find = jdbcSession.findPage(Customer.class)
                .eq(jsonObject, "contactName", "customerType", "customerStatus", "customerSource")
                .eq("firstContact", true)
                .like(jsonObject, "corpFullName", "corpName", "mobile")
                .eq("deleted", false);
        //添加选中导出条件
        JSONArray exportIdList = jsonObject.getJSONArray("exportIdList");
        if(!Objects.isEmpty(exportIdList)){
            find.in("id",exportIdList);
        }
        return find.order("createTime", "desc").page(jsonObject).exe();
    }

    /**
     * 获取客户列表
     * @param jsonObject 查询对象
     * @return 客户列表
     */
    @ReqMapping("/list")
    @Override
    public Object list(JSONObject jsonObject) {
        return jdbcSession.findArray(Customer.class)
                .eq(jsonObject, "id","contactName")
                .like(jsonObject, "corpFullName", "corpName", "mobile")
                .eq("deleted", false)
                .eq("firstContact",true)
                .order("createTime", "desc")
                .exe();
    }

    /**
     * 新增客户
     *
     * @param token
     * @param  customer 新增
     * @param contact
     * @return success
     */
    @Bean(newInstance = true, copy = true)
    @ReqMapping("/save")
    @Override
    public Object save(Token token, Customer customer, Contact contact) throws Exception {
        checkSave(customer);
        customer.setCreateBy(token.getName());
        customer.setFirstContact(true);
        jdbcSession.insert(customer);
        buildContact(customer,contact);
        jdbcSession.insert(contact);
        customer.setContactId(contact.getId());
        jdbcSession.updateById(customer);
        customerRecordService.saveOrUpdate(customer,token);
        return Result.success(customer);
    }

    private void buildContact(Customer customer, Contact contact) {
        contact.setContactName(customer.getContactName());
        contact.setCustomerId(customer.getId());
        contact.setCorpFullName(customer.getCorpFullName());
        contact.setSirOrLady(customer.getSirOrLady());
        contact.setRole(customer.getRole());
        contact.setBirthday(customer.getBirthday());
        contact.setPosition(customer.getPosition());
        contact.setMobile(customer.getMobile());
        contact.setTelephone(customer.getTelephone());
        contact.setFax(customer.getFax());
        contact.setEmail(customer.getEmail());
        contact.setWechat(customer.getWechat());
        contact.setQq(customer.getQq());
        contact.setAreaName(customer.getAreaName());
        contact.setDetailAddress(customer.getDetailAddress());
        contact.setRemarkMsg(customer.getRemarkMsg());
        contact.setFollowUpName(customer.getFollowUpName());
        contact.setFollowUpId(customer.getFollowUpId());
        contact.setFirstContact(customer.isFirstContact());
        contact.setLastFollowUpTime(customer.getLastFollowUpTime());
    }


    @ReqMapping("/checkSave")
    private void checkSave(Customer customer) {
        Customer isExistCustomer = jdbcSession.findOne(Customer.class)
                .eq("corpFullName", customer.getCorpFullName())
                .eq("deleted", false)
                .exe();
        if(Objects.nonNull(isExistCustomer)){
            throw new RuntimeException("客户名已经存在.");
        }
    }

    /**
     * 编辑客户
     * @param  customer 编辑
     * @param token
     * @return success
     */
    @Bean(copy = true)
    @ReqMapping("/update")
    @Override
    public Object update(Customer customer, Token token) throws Exception {
        Customer oldCustomer = Pool.get(Customer.class, customer.getId());
        String oldBelongId = oldCustomer.getCustomerBelongId();
        jdbcSession.updateById(customer);
        Contact contact = jdbcSession.findOne(Contact.class).eq("id", customer.getContactId()).eq("deleted", false).exe();
        if (Objects.nonNull(contact)) {
            buildContact(customer,contact);
            jdbcSession.updateById(contact);
        }
        //更新客户归属
        String newBelongId = customer.getCustomerBelongId();
        if (Objects.nonNull(oldBelongId) && Objects.nonNull(newBelongId) && !oldBelongId.equals(newBelongId)) {
            customerRecordService.saveOrUpdate(customer,token);
        }
        return Result.success(customer);
    }

    /**
     * 删除客户
     * @param  customer 删除
     * @return success
     */
    @ReqMapping("/delete")
    @Override
    public Object delete(Customer customer) {
        String id = customer.getId();
        customer.setDeleted(true);
        jdbcSession.updateById(customer,customer.getId());
        List<Contact> contactList = jdbcSession.findArray(Contact.class).eq("customerId", id).exe();
        List<String> contactIdList = new ArrayList<>();
        if (java.util.Objects.nonNull(contactList)) {
           contactList.forEach(item ->{
               item.setDeleted(true);
           });
            contactIdList = contactList.stream().map(Contact::getId).distinct().collect(Collectors.toList());
            jdbcSession.updateById(contactList);
        }
        List<ContactDynamics> dynamics = jdbcSession.findArray(ContactDynamics.class).in("contactId", contactIdList).eq("deleted", false).exe();
        if (java.util.Objects.nonNull(dynamics)) {
            dynamics.forEach(item ->{
                item.setDeleted(true);
            });
            jdbcSession.updateById(dynamics);
        }
        customerRecordService.delete(customer);
        return Result.success();
    }
}
